package com.heima.user.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取userId
        String userId = request.getHeader("userId");
        // 判断userId不为空且不等于0
        if (!StringUtils.isEmpty(userId) && !userId.equals("0")) {
            // 将用户信息放入到本地线程中
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            MediaThreadLocalUtil.set(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 释放本地线程
        MediaThreadLocalUtil.remove();
    }
}
